import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'
import store from '@/store'
import Home from '@/views/menu/Home.vue'
import UserInfo from '@/views/menu/user/userInfo.vue'
import UserAvatar from '@/views/menu/user/userAvatar.vue'
import UserPwd from '@/views/menu/user/UserPwd.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  // 路由规则的数组,
  routes: [
    // 注册页面的路由规则
    { path: '/reg', component: Reg },
    // 登陆页面的路由规则
    { path: '/login', component: Login },
    // 后台主页得到路由规则
    { path: '/', component: Main, redirect: '/home', children: [{ path: 'home', component: Home }, { path: 'user-info', component: UserInfo }, { path: 'user-avatar', component: UserAvatar }, { path: 'user-pwd', component: UserPwd }] }
    // 定义完规则要在页面中写入路由占位符
  ]
})
// 声明全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/reg' || to.path === '/login') {
    next()
  } else {
    const token = store.state.muser.token
    if (token === '') {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
